package com.example.compreshensiveshop.intercept;

import com.example.compreshensiveshop.utils.JwtUtil;


import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;




@Component
@Slf4j
public class JwtInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String requestURI = request.getRequestURI();
        String method = request.getMethod();
        System.out.println("=== JWT拦截器被调用，请求路径: " + requestURI + ", 方法: " + method + " ===");
        System.out.println("=== 请求头Authorization: " + request.getHeader("Authorization") + " ===");

        // 1. 获取请求头中的 Token
        String token = request.getHeader("Authorization");
        if (token == null || !token.startsWith("Bearer ")) {
            // 没有 Token 或格式不对，返回false，拒绝访问
            System.out.println("=== 请求路径 " + requestURI + " 缺少有效 Token，返回401 ===");
            log.info("缺少有效 Token: {}", token);
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            response.setContentType("application/json;charset=UTF-8");
            response.getWriter().write("{\"code\":401,\"message\":\"缺少有效 Token\"}");
            return false;
        }
        token = token.replace("Bearer ", "");

        // 2. 校验 Token
        if (!JwtUtil.validateToken(token)) {
            log.info("Token 无效");
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            response.setContentType("application/json;charset=UTF-8");
            response.getWriter().write("{\"code\":401,\"message\":\"Token 无效\"}");
            return false;
        }

        Long userId = JwtUtil.getUserIdFromToken(token);
        request.setAttribute("userId", userId);
        Long customerId = JwtUtil.getCustomerIdFromToken(token);
        Long sellerId = JwtUtil.getSellerIdFromToken(token);
        if (customerId != null) request.setAttribute("customerId", customerId);
        if (sellerId != null) request.setAttribute("sellerId", sellerId);
        return true;
    }
}
